import {
  Form, Input, Radio, Tree,
} from 'antd'
import React, {
  useCallback, useEffect, useImperativeHandle, useState,
} from 'react'
import { postAddAdminApi, postAddUpdataApi } from '../../../api/auth'
import menu from '@/router/menu'

const AdminForm = React.forwardRef((props, ref) => {
  
  const { detail } = props
  // console.log(detail)
  const [form] = Form.useForm()
  // 权限是否显示
  const [role, setRole] = useState(1)
  const handleVluesChange = useCallback((values) => {
    if (values.role) setRole(values.role)
  }, [])
  // 提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields()
      if (detail) {
        await postAddUpdataApi(values)
      } else {
        await postAddAdminApi(values)
      }
      return true
    } catch (error) {
      console.log(error)
      return null
    }
  }, [detail])
  // 通过ref modal 传递提交并并访问接口方法
  useImperativeHandle(
    ref,
    () => ({ submit: handleSubmit, clear: () => form.setFieldsValue({ role, checkedKeys: [] }) }),
    [detail],
  )
  useEffect(() => {
    console.log(detail, 'dedede')
    if (detail) {
      console.log(detail)
      form.setFieldsValue({ ...detail })
    } else {
      form.setFieldsValue({ role, checkedKeys: [] })
    }
  }, [detail])
  return (
    <Form form={form} labelCol={{ span: 4 }} onValuesChange={handleVluesChange}>
      <Form.Item label="用户名" name="adminname" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      {
        !detail && (
          <>
            <Form.Item label="密码" name="password" rules={[{ required: true }]}>
              <Input type="password" />
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="gg"
              rules={[{ required: true }, ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次密码不一致哦!'));
                },
              })]}
            >
              <Input type="password" />
            </Form.Item>
          </>
        )
      }
      <Form.Item label="角色" name="role" rules={[{ required: true }]}>
        <Radio.Group>
          <Radio value={1}>管理员</Radio>
          <Radio value={2}>超级管理员</Radio>
        </Radio.Group>

      </Form.Item>
      {role !== 2 && (
        <Form.Item label="权限" name="checkedKeys" valuePropName="checkedKeys" trigger="onCheck">
          <Tree
            checkable
            defaultExpandAll
            treeData={menu}
          />
        </Form.Item>
      )}
    </Form>

  )
})
export default AdminForm
